using System;
using System.IO;
using Microsoft.Isam.Esent.Collections.Generic;

namespace SG.Lang.Dry.Base
{
    public static class Repository<TElement>
        where TElement : struct
    {
// ReSharper disable StaticFieldInGenericType
        private static readonly PersistentDictionary<Guid, TElement> Elements;
// ReSharper restore StaticFieldInGenericType

        static Repository()
        {
            var @base = Repository.BaseDirectory;
            if (@base == null)
                return;

            Repository.OnApplicationExit += Repositry_OnApplicationExit;
            var type = typeof (TElement).Name;
            Elements = new PersistentDictionary<Guid, TElement>(Path.Combine(@base, type));     
        }

        public static bool TryGet(ref Guid guid, out TElement element)
        {
            if (Elements != null)
                return Elements.TryGetValue(guid, out element);
            
            element = default(TElement);
            return false;
        }


        static void Repositry_OnApplicationExit(object sender, EventArgs e)
        {
            if (Elements == null)
                return;

            Elements.Dispose();
        }
    }

    public static class Repository
    {
        public static string BaseDirectory { get; set; }

        public static event EventHandler OnApplicationExit;
    }
}